package com.dats.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 * @author sig
 * @since 2016/10/5
 */
public class ExcelParser {

    public static List<String> getStringList(String fileName) {
        List<String> list = new ArrayList<>();

        try {
            FileInputStream in = new FileInputStream(fileName);
            Workbook workbook = getWorkbook(in, fileName);
            Sheet sheet = workbook.getSheetAt(0);

            for (int pos = 0, rows = sheet.getPhysicalNumberOfRows();
                 pos < rows; pos++) {
                StringJoiner joiner = new StringJoiner("\t");
                Row row = sheet.getRow(pos);

                for (int pos2 = 0, cells = sheet.getRow(0)
                        .getPhysicalNumberOfCells(); pos2 < cells; pos2++) {
                    Cell cell = row.getCell(pos2);

                    if (null == cell) continue;
                    String value = "";

                    switch (cell.getCellType()) {
                        case 0:
                            value = String.valueOf(
                                    cell.getNumericCellValue());
                            break;
                        case 1:
                            value = cell.getStringCellValue();
                            break;
                        default:
                            break;
                    }
                    joiner.add(value);
                }
                list.add(joiner.toString());
            }
        } catch (Exception e) {
            LogUtil.console.error(e.getMessage(), e);
        }
        return list;
    }

    private static Workbook getWorkbook(InputStream in,
                                        String name) throws IOException {
        return name.endsWith(".xlsx") ? new XSSFWorkbook(in) : new HSSFWorkbook(in);
    }
}
